package admin

// by daoyi
import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"simai_oa/controller"
	"simai_oa/model"
	"simai_oa/tool"
	"simai_oa/tool/convert"
	"strconv"
)

type Menu struct{}

// List
//
//	@Summary	分页数据
//	@Tags		后台-导航栏
//	@param		page		query		int		false	"多少页"
//	@param		limit		query		int		false	"每页多少条"
//	@param		sort		query		string	false	"排序"
//	@param		key			query		string	false	"搜索条件"
//	@param		type		query		string	false	"导航类型"
//	@param		parent_id	query		string	false	"父id"
//	@Success	200			{string}	json{"code","message","data"}
//	@Router		/admin/menu/list [GET]
func (Menu) List(c *gin.Context) {
	page := controller.GetPageIndex(c)
	limit := controller.GetPageLimit(c)
	sort := controller.GetPageSort(c)
	key := controller.GetPageKey(c)
	menuType := controller.GetQueryToUint(c, "type")
	parent_id := controller.GetQueryToUint64(c, "parent_id")
	var whereOrder []model.PageWhereOrder
	order := "ID DESC"
	if len(sort) >= 2 {
		orderType := sort[0:1]
		order = sort[1:len(sort)]
		if orderType == "+" {
			order += " ASC"
		} else {
			order += " DESC"
		}
	}
	whereOrder = append(whereOrder, model.PageWhereOrder{Order: order})
	if key != "" {
		v := "%" + key + "%"
		var arr []interface{}
		arr = append(arr, v)
		arr = append(arr, v)
		whereOrder = append(whereOrder, model.PageWhereOrder{Where: "name like ? or code like ?", Value: arr})
	}
	if menuType > 0 {
		var arr []interface{}
		arr = append(arr, menuType)
		whereOrder = append(whereOrder, model.PageWhereOrder{Where: "menu_type = ?", Value: arr})
	}
	if parent_id > 0 {
		var arr []interface{}
		arr = append(arr, parent_id)
		whereOrder = append(whereOrder, model.PageWhereOrder{Where: "parent_id = ?", Value: arr})
	}
	var total int64
	list := []model.Menu{}
	err := model.GetPage(&model.Menu{}, &model.Menu{}, &list, page, limit, &total, whereOrder...)
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	controller.ResSuccessPage(c, total, &list)
}

// Detail
//
//	@Summary	详情
//	@Tags		后台-导航栏
//	@param		id	query		int	false	"id"
//	@Success	200	{string}	json{"code","message","data"}
//	@Router		/admin/menu/detail [GET]
func (Menu) Detail(c *gin.Context) {
	id := controller.GetQueryToUint64(c, "id")
	var menu model.Menu
	where := model.Menu{}
	where.ID = id
	_, err := model.First(&where, &menu)
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	controller.ResSuccess(c, &menu)
}

// Update
//
//	@Summary	更新
//	@Tags		后台-导航栏
//	@param		id				query		int	false	"id"
//	@param		status			query		int	false	"状态(1:启用 2:不启用)"
//	@param		memo			query		int	false	"备注"
//	@param		parent_id		query		int	false	"父级ID"
//	@param		url				query		int	false	"菜单URL"
//	@param		name			query		int	false	"菜单名称"
//	@param		sequence		query		int	false	"排序值"
//	@param		menu_type		query		int	false	"菜单类型 1模块2菜单3操作"
//	@param		code			query		int	false	"菜单代码"
//	@param		icon			query		int	false	"icon"
//	@param		operate_type	query		int	false	"操作类型 none/add/del/view/update"
//	@Success	200				{string}	json{"code","message","data"}
//	@Router		/admin/menu/update [POST]
func (Menu) Update(c *gin.Context) {
	models := model.Menu{}
	err := c.Bind(&models)
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	err = model.Save(&models)
	if err != nil {
		log.Println(err)
		controller.ResFail(c, "操作失败")
		return
	}
	controller.ResSuccessMsg(c)
}

// Create
//
//	@Summary	新增
//	@Tags		后台-导航栏
//	@param		status			query		uint8	false	"状态(1:启用 2:不启用)"
//	@param		memo			query		string	false	"备注"
//	@param		parent_id		query		uint8	false	"父级ID"
//	@param		url				query		string	false	"菜单URL"
//	@param		name			query		string	false	"菜单名称"
//	@param		sequence		query		uint8	false	"排序值"
//	@param		menu_type		query		uint8	false	"菜单类型 1模块2菜单3操作"
//	@param		code			query		string	false	"菜单代码"
//	@param		icon			query		string	false	"icon"
//	@param		operate_type	query		string	false	"操作类型 none/add/del/view/update"
//	@Success	200				{string}	json{"code","message"}
//	@Router		/admin/menu/create [POST]
func (Menu) Create(c *gin.Context) {
	menu := model.Menu{}
	err := c.Bind(&menu)
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}

	fmt.Println(menu)
	err = model.Create(&menu)
	if err != nil {
		log.Println(err)
		controller.ResFail(c, "操作失败")
		return
	}
	//go InitMenu(menu)
	controller.ResSuccess(c, gin.H{"id": menu.ID})
}

// Delete
//
//	@Summary	删除数据
//	@Tags		后台-导航栏
//	@param		ids	query		int	false	"ids"
//	@Success	200	{string}	json{"code","message"}
//	@Router		/admin/menu/delete [POST]
func (Menu) Delete(c *gin.Context) {
	var ids []uint64
	err := c.Bind(&ids)
	if err != nil || len(ids) == 0 {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	menu := model.Menu{}
	err = menu.Delete(ids)
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	controller.ResSuccessMsg(c)
}

// AllMenu
// @Summary	所有菜单
// @Tags		后台-导航栏
// @Success	200	{string}	json{"code","message","data"}
// @Router		/admin/menu/allmenu [GET]
func (Menu) AllMenu(c *gin.Context) {
	var menus []model.Menu
	err := model.Find(&model.Menu{}, &menus, "parent_id asc", "sequence asc")
	if err != nil {
		log.Println(err)
		controller.ResErrSrv(c, err)
		return
	}
	controller.ResSuccess(c, &menus)
}

// 新增菜单后自动添加菜单下的常规操作
func InitMenu(models model.Menu) {
	if models.MenuType != 2 {
		return
	}
	add := model.Menu{Status: 1, ParentID: models.ID, URL: models.URL + "/create", Name: "新增", Sequence: 1, MenuType: 3, Code: models.Code + "Add", OperateType: "add"}
	model.Create(&add)
	del := model.Menu{Status: 1, ParentID: models.ID, URL: models.URL + "/delete", Name: "删除", Sequence: 2, MenuType: 3, Code: models.Code + "Del", OperateType: "del"}
	model.Create(&del)
	view := model.Menu{Status: 1, ParentID: models.ID, URL: models.URL + "/detail", Name: "查看", Sequence: 3, MenuType: 3, Code: models.Code + "View", OperateType: "view"}
	model.Create(&view)
	update := model.Menu{Status: 1, ParentID: models.ID, URL: models.URL + "/update", Name: "编辑", Sequence: 4, MenuType: 3, Code: models.Code + "Update", OperateType: "update"}
	model.Create(&update)
	list := model.Menu{Status: 1, ParentID: models.ID, URL: models.URL + "/list", Name: "分页api", Sequence: 5, MenuType: 3, Code: models.Code + "List", OperateType: "list"}
	model.Create(&list)
}

// MenuList
//
//	@Summary	获取有权限的菜单
//	@Tags		后台-导航栏
//	@Success	200			{string}	json{"code","message","data"}
//	@Router		/admin/menu/menulist [GET]
func (Menu) MenuList(c *gin.Context) {
	// 用户ID
	token, _ := tool.GetTokenFromRequest(c)
	uID := tool.GetValueFromTokenClaims("Id", token.Claims)
	gID := tool.GetValueFromTokenClaims("GameId", token.Claims)
	uid, _ := strconv.Atoi(uID)
	userID := convert.ToUint64(uid)
	//gid, _ := strconv.Atoi(gID)
	//gameId := convert.ToUint64(gid)
	if userID == 0 {
		controller.ResFail(c, "err1")
		return
	}
	var menu []model.Menu

	var rmenu []model.RoleMenu
	tool.Gdb.Table("za_role_menu").Where("role_id = ?", gID).Select("menu_id").Find(&rmenu)
	var menuIds []uint64
	for _, roleMenu := range rmenu {
		menuIds = append(menuIds, roleMenu.MenuID)
	}

	if userID != controller.SUPER_ADMIN_ID {
		//管理员
		err := tool.Gdb.Where("operate_type = ? and parent_id = ? and id in (?)", "none", 1, menuIds).Find(&menu).Error

		if err != nil {
			log.Println(err)
			controller.ResErrSrv(c, err)
			return
		}

		for idx := range menu {
			var childOrders []model.Menu
			tool.Gdb.Where("operate_type = ? and parent_id = ? and id in (?)", "none", menu[idx].ID, menuIds).Find(&childOrders)
			menu[idx].Menu = childOrders
		}

	} else {
		err := tool.Gdb.Where("operate_type = ?", "none").Find(&menu).Error
		if err != nil {
			log.Println(err)
			controller.ResErrSrv(c, err)
			return
		}
	}
	controller.ResSuccess(c, &menu)
}
